var app = getApp();

var common = require("../../../common/common.js").common;

var un = require("../../../siteinfo.js");

Page({
    data: {
        formats: {},
        readOnly: false,
        placeholder: "开始输入...",
        editorHeight: 300,
        keyboardHeight: 0,
        isIOS: false
    },
    readOnlyChange() {
        this.setData({
            readOnly: !this.data.readOnly
        });
    },
    onLoad(options) {
        let pages = getCurrentPages();
        let prevPage = pages[pages.length - 2];
        this.setData({
            detail: prevPage.data.detail
        });
        const platform = wx.getSystemInfoSync().platform;
        const isIOS = platform === "ios";
        this.setData({
            isIOS: isIOS
        });
        const that = this;
        this.updatePosition(0);
        let keyboardHeight = 0;
        wx.onKeyboardHeightChange(res => {
            if (res.height === keyboardHeight) return;
            const duration = res.height > 0 ? res.duration * 1e3 : 0;
            keyboardHeight = res.height;
            setTimeout(() => {
                wx.pageScrollTo({
                    scrollTop: 0,
                    success() {
                        that.updatePosition(keyboardHeight);
                        that.editorCtx.scrollIntoView();
                    }
                });
            }, duration);
        });
    },
    updatePosition(keyboardHeight) {
        const toolbarHeight = 50;
        const {windowHeight: windowHeight, platform: platform} = wx.getSystemInfoSync();
        let editorHeight = keyboardHeight > 0 ? windowHeight - keyboardHeight - toolbarHeight : windowHeight;
        this.setData({
            editorHeight: editorHeight,
            keyboardHeight: keyboardHeight
        });
    },
    calNavigationBarAndStatusBar() {
        const systemInfo = wx.getSystemInfoSync();
        const {statusBarHeight: statusBarHeight, platform: platform} = systemInfo;
        const isIOS = platform === "ios";
        const navigationBarHeight = isIOS ? 44 : 48;
        return statusBarHeight + navigationBarHeight;
    },
    onEditorReady() {
        const that = this;
        wx.createSelectorQuery().select("#editor").context(function(res) {
            that.editorCtx = res.context;
            that.editorCtx.setContents({
                html: that.data.detail,
                success: function() {},
                fail: function(e) {}
            });
        }).exec();
    },
    blur() {
        this.editorCtx.blur();
    },
    format(e) {
        let {name: name, value: value} = e.target.dataset;
        if (!name) return;
        // console.log('format', name, value)
                this.editorCtx.format(name, value);
    },
    onStatusChange(e) {
        const formats = e.detail;
        this.setData({
            formats: formats
        });
    },
    insertDivider() {
        this.editorCtx.insertDivider({
            success: function() {
                console.log("insert divider success");
            }
        });
    },
    clear() {
        this.editorCtx.clear({
            success: function(res) {
                console.log("clear success");
            }
        });
    },
    removeFormat() {
        this.editorCtx.removeFormat();
    },
    insertDate() {
        const date = new Date();
        const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`;
        this.editorCtx.insertText({
            text: formatDate
        });
    },
    insertImage() {
        const that = this;
        this.uploadImage();
    },
    //上传图片
    uploadImage: function(e) {
        var that = this;
        let domian = app.globalData.domain;
        let count = 1;
        let uniacid;
        if (wx.getStorageSync("uniacid")) {
            uniacid = wx.getStorageSync("uniacid");
        } else {
            uniacid = un.uniacid;
        }
        wx.chooseImage({
            count: count,
            //最多可以选择的图片总数
            sizeType: [ "compressed" ],
            // 可以指定是原图还是压缩图，默认二者都有
            sourceType: [ "album", "camera" ],
            // 可以指定来源是相册还是相机，默认二者都有
            success: function(res) {
                // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                var tempFilePaths = res.tempFilePaths;
                //启动上传等待中...
                                wx.showLoading({
                    title: "正在上传..."
                });
                var i = 0;
                var length = tempFilePaths.length;
                var upload = function() {
                    wx.uploadFile({
                        url: domian + "Lodger/lodger/product-img-upload",
                        filePath: tempFilePaths[i],
                        name: "file",
                        formData: {},
                        header: {
                            "Content-Type": "multipart/form-data",
                            uniacid: uniacid
                        },
                        success: function(res) {
                            var data = JSON.parse(res.data);
                            i++;
                            if (i < length) {
                                upload();
                            } else {
                                that.editorCtx.insertImage({
                                    src: data.extra.url,
                                    data: {
                                        id: "abcd",
                                        role: "god"
                                    },
                                    width: "80%",
                                    success: function() {
                                        console.log("insert image success");
                                        wx.hideLoading();
                                    }
                                });
                            }
                        },
                        fail: function(res) {
                            wx.hideToast();
                            wx.showModal({
                                title: "错误提示",
                                content: "上传图片失败",
                                showCancel: false,
                                success: function(res) {}
                            });
                        }
                    });
                };
                upload();
            }
        });
    },
    goBack: function() {
        this.editorCtx.getContents({
            success: res => {
                let pages = getCurrentPages();
                let prevPage = pages[pages.length - 2];
                prevPage.setData({
                    detail: res.html
                });
                wx.navigateBack({});
            }
        });
    }
});